// pages/home/person.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    imgPath: 'http://qnstatic.lianhequnmei.com/images',
    name: '',
    mobile: '1768*****115',
    head_image: '',

    //服务计划剩余天数59天
    leftDays: 90,

    //已守护您的宝宝100天
    protectedDays: 100,

    //个人中心
    home: null,

    //已完成进度
    finishPercent: 25,

    cardOnsale: {},


    nowDate: '2023-03-22 18:00:00', //结束时间
    countdown: '', //倒计时
    monthCount: '00', //月
    dayCount: '00', //天
    hoursCount: '00', //时
    minutesCount: '00', //分
    secondsCount: '00', //秒

    flag:false,

    is_anchor:0

  },

  /**
   * 组件的方法列表
   */
  methods: {
    anchorList(){
      wx.navigateTo({
        url: '/pages/livebroadcast/livebroadcast',
      })
      return;
    },
    modifyHeadImage() {
      wx.navigateTo({
        url: '/pages/info/info',
      })
      return;
    },
    chengZhang() {
      wx.showToast({
        title: '成长计划',
      })
    },
    renew() {
      // wx.showToast({
      //   title: '续费',
      // })
      wx.navigateTo({
        url: '/pages/service/JiHuaXuFei',
      })
    },
    about() {
      wx.navigateTo({
        url: '/pages/home/ljmjl',
      })
    },
    shippingAddress() {
      // wx.navigateTo({
      //   url: '/pages/shippingAddress/list',
      // })
      const api = require("../../api/api")
      api.user.chooseAddress({
        success(res) {
          console.log("chooseAddress,success,res", res)
        },
        fail(res) {
          console.log("chooseAddress,fail,res", res)
        },
        complete(res) {
          console.log("chooseAddress,complete,res", res)
        }
      })
    },
    couponList() {
      wx.navigateTo({
        url: '/pages/coupon/list',
      })
    },
    contact() {
      // wx.navigateTo({
      //   url: '/pages/customerService/index',
      // })
      //写入回调地址
      wx.setStorageSync('im:redirectUrl', "");
      
      wx.navigateTo({
        url: '/im/pages/index?type=kefu&iskefu=true',
      })
        // wx.navigateTo({
        //   url: '/pages/consultants/consultants',
        // })


    },
    chengZhang() {
      wx.navigateTo({
        url: '/pages/chengZhangKa/index?refresh=1',
      })
    },
    myOrderSheet() {
      wx.navigateTo({
        url: '/pages/orderSheet/myOrderSheet',
      })
    },
    /**
     * 关注公众号
     */
    payAttention() {
      wx.navigateTo({
        url: '/pages/person/attention',
      })
    },
    calLeftDays() {

      //剩余天数
     // console.log("this.data.home", this.data.home)
      let home = this.data.home;
      let dtNow = new Date();
      let card_start_time = new Date(home.member_card_info.start_time)
      let card_end_time = new Date(home.member_card_info.end_time);
      let card_diff = Number(card_end_time) - Number(dtNow);
      let card_diff_days = Math.round(Number(card_diff) / (24 * 60 * 60 * 1000));

      //总天数
      let totalDays = (Number(card_end_time) - Number(card_start_time)) / (24 * 60 * 60 * 1000);

      //使用百分比
      let finishPercent = Math.round((totalDays - card_diff_days) / totalDays * 100)
      let member_remain_days = home.member_card_info.member_remain_days;
      this.setData({
        leftDays: member_remain_days,
        finishPercent: finishPercent,
      })


    },
    calProtectedDay() {
    //  console.log("this.data.home", this.data.home)
      let home = this.data.home;
      let dtNow = new Date();
      let card_start_time = new Date(home.member_card_info.start_time);
      let card_diff = Number(dtNow) - Number(card_start_time);
      let card_diff_days = Math.round(Number(card_diff) / (24 * 60 * 60 * 1000));
      let defend_baby_days = home.member_card_info.defend_baby_days;
      this.setData({
        protectedDays: defend_baby_days,
      })
    },
    countTime(dateStr) {
      let that = this;
      let now = new Date();
      console.log('now',now);
      let end = new Date(dateStr);
      let diffTime = +end - +now;
      if (diffTime < 0) {
        that.setData({
          flag:true
        });
        return;
      }
      // 获取剩余时间的天、时、分、秒；
      let dayCount = Math.floor(diffTime / (1000 * 3600 * 24));
      let hoursCount = Math.floor(diffTime / (1000 * 3600) % 24);
      let minutesCount = Math.floor(diffTime / (1000 * 60) % 60);
      let secondsCount = Math.floor(diffTime / 1000 % 60);
      // 获取剩余的月份
      let monthCount = (end.getFullYear() - now.getFullYear()) * 12 + (end.getMonth() - now.getMonth());
      let _end = new Date(+end);
      _end.setMonth(_end.getMonth(), 0);
      let lastMonthDayCount = end.getDate() + (_end.getDate() - now.getDate());
      let isOverCurrentTime = end.getTime() % (1000 * 3600 * 24) < now.getTime() % (1000 * 3600 * 24);
      if (end.getDate() < now.getDate()) {
        monthCount -= 1;
        dayCount = lastMonthDayCount;
      } else if (end.getDate() > now.getDate()) {
        dayCount = end.getDate() - now.getDate()
      } else {
        if (isOverCurrentTime) {
          monthCount -= 1;
          dayCount = lastMonthDayCount;
        } else {
          dayCount = end.getDate() - now.getDate();
        }
      }
      if (isOverCurrentTime) {
        dayCount -= 1;
      }
      that.setData({
        countdown: monthCount + ":" + dayCount + ":" + hoursCount + "：" + minutesCount + "：" + secondsCount,
        monthCount,
        dayCount,
        hoursCount,
        minutesCount,
        secondsCount
      })
    },
    getserver(){
      wx.navigateTo({
        url: '/pages/plan/joinPlan?renew=true',
      })
    },
    userCard() {
      wx.navigateTo({
        url: '/pages/chengZhangKa/index',
      })
    },
    closepop(){
      this.setData({
        flag:false
      });
    },
    liJiXuFei() {

      // this.setData({
      //   flag:true
      // });
      // return;
      wx.navigateTo({
        url: '/pages/plan/joinPlan?renew=true',
      })

      return;
   
      wx.showLoading({
        title: '加载中',
        icon: 'loading'
      });
      // wx.showToast({
      //   title: '立即续费'+this.data.price,
      // })
      const api = require("../../api/api")
      const util = require("../../utils/util");
      api.order.transactions({
        goods_info: [{
          goods_id: this.data.cardOnsale.id,
          buy_number: 1,
          coupon_id: "",
          channel: util.getChannel(),
        }],
        price: this.data.cardOnsale.price,
        success(res) {
          wx.hideLoading();
          // console.log("transactions.res", res)
          let order_sn = res.data.data.order_sn;
          api.order.payment({
            order_sn: order_sn,
            pay_type: 'wx',
            pay_client: 'lite',
            success(resPayment) {
              // console.log("payment,resPayment", resPayment)

              let dataPayment = resPayment.data.data;

              //微信支付
              wx.requestPayment({
                timeStamp: dataPayment.timeStamp,
                nonceStr: dataPayment.nonceStr,
                package: dataPayment.package,
                signType: 'MD5',
                paySign: dataPayment.paySign,
                success(resPay) {
                  // console.log("wx.requestPayment,success,resPay", resPay)

                  //支付成功
                  wx.navigateTo({
                    url: '/pages/orderSheet/paySuccess',
                  })
                },
                fail(resPay) {
                  // console.log("wx.requestPayment,fail,resPay", resPay);
                  //支付失败

                  //调订单删除接口
                  api.user.orderDelete({
                    order_sn: order_sn,
                    success(resDel) {
                      // console.log("orderDelete,resDel",resDel)
                    }
                  })

                  wx.navigateTo({
                    url: '/pages/orderSheet/payFail?jp=/pages/plan/joinPlan',
                  })
                }
              })
            }
          })
        }
      })
      // wx.navigateTo({
      //   url: '/pages/orderSheet/paying',
      // })
    },
  },
  lifetimes: {
    attached() {
      const util = require("../../utils/util")
      let that = this;
      // this.setData({
      //   imgPath: util.getImgPath()
      // })
      // this.setData({
      //   remainTime: this.data.endTime - this.data.nowTime
      // })
      // util.countDown(this); 
      wx.setNavigationBarTitle({
        title: '个人中心',
      })
      let home = wx.getStorageSync('home');
      let userInfo = wx.getStorageSync('userInfo');
      const api = require("../../api/api");
      api.user.home({
        success(res) {
          if(res.data.code == 0){
              //保存home到缓存
              that.setData({
                home: res.data.data,
                name: res.data.data.nickname,
                mobile: '',
                head_image: res.data.data.head_image + '?v=' + Date.now(),
                is_anchor:res.data.data.is_anchor
              })
                // 服务剩余时间倒计时
               that.countTime(res.data.data.member_card_info.end_time);

                    //计划服务计划剩余天数
               that.calLeftDays();

                //计算已守护您的宝宝天数
                that.calProtectedDay();


          }
    
        }
      })
     // console.log('userInfo', Object.keys(userInfo).length);
 
      // if (Object.keys(userInfo).length == 0) {
     
      // } else {
      //   this.setData({
      //     home: home,
      //     name: userInfo.nickName,
      //     mobile: '',
      //     head_image: userInfo.avatarUrl,
      //   })
      // }


 

    

    }
  }
})